import { store } from "./redux/store"
import { useRealm } from '@realm/react'
import { schemaName } from "./realm"
import Realm from "realm"
import httpApi from "./api"
import SplashScreen from 'react-native-splash-screen';


export default loadFromLocalStorages = (isOadFromLocalStorages = true) => {

    // if (isLoadingLoadFrom) return
    const realm = useRealm();
    const loadInitialData = async () => {
        const { isLoadingLoadFrom } = store.getState().app

        if (isLoadingLoadFrom) return
        store.dispatch((dispatch) => {
            dispatch({ type: 'app/setIsLoadingLoadFrom', payload: true })
        })
        const userInfo = realm.objects(schemaName.UserInfo).filtered('Current = true')[0]
        const UserId = userInfo?.Id || 0
        if (!!UserId) {
            try {
                const getUserInfo = await httpApi.getUserInfo()
                realm.write(() => {
                    realm.create(schemaName.UserInfo, { ...getUserInfo.data.UserInfo, Token: getUserInfo.data.Token }, true);
                });
                const FriendMsgSeq = realm.objects(schemaName.FriendMsgSeq).filtered(`UserId == ${UserId}`)[0]
                const FriendMsgLis = realm.objects(schemaName.FriendMsgLis).filtered(`UserId == ${UserId}`)
                const getFriendList = await httpApi.getFriendList()
                const groupList = (await httpApi.getGroupList()).data.GroupList
                const Msgs = (await httpApi.getFriendMsg({ seq: Math.max(getUserInfo.data.UserInfo.FriendSeq, FriendMsgSeq?.Cur || 0), num: getUserInfo.data.TotalSeq })).data.Msgs
                realm.write(() => {
                    getFriendList.data.FriendList && getFriendList.data.FriendList.map(item => realm.create(schemaName.FriendList, { ...item, UserId, State: 1 }, true))
                    groupList && groupList.map(item => realm.create(schemaName.GroupList, { ...item, UserId, State: 1 }, true))
                    Msgs && Msgs.map(item => {
                        if ([45].indexOf(item.MT) === -1) {
                            realm.create(schemaName.FriendMsgLis, { ...item, _id: new Realm.BSON.UUID(), UserId }, true)
                        }
                    })
                    realm.create(schemaName.FriendMsgSeq, { Cur: getUserInfo.data.TotalSeq, Total: getUserInfo.data.TotalSeq, UserId }, true);
                    httpApi.setFriendSeq({ seq: Math.max(getUserInfo.data.TotalSeq, FriendMsgSeq?.Cur || 0) - 20 })

                })
                let groupListMsg = []
                for (let index = 0; index < groupList?.length; index++) {
                    const element = groupList[index];
                    let GroupMsgSeq = realm.objects(schemaName.GroupMsgSeq).filtered(`G ==${element.G} and UserId == ${UserId}`)[0]
                    if ((GroupMsgSeq?.Cur || 0) !== element.U) {
                        const res = await httpApi.getGroupMsg({ groupId: element.G, seq: Math.max(element.S, GroupMsgSeq?.Cur || 0), num: element.U })
                        groupListMsg = groupListMsg.concat(res.data.Msgs || [])
                        realm.write(async () => {
                            httpApi.setGroupSeq({ groupId: element.G, seq: Math.max(element.S, GroupMsgSeq?.Cur || 0) - 20 })
                            realm.create(schemaName.GroupMsgSeq, { _id: GroupMsgSeq?._id || new Realm.BSON.UUID(), G: element.G, Cur: element.U, Total: element.U, UserId: UserId }, true);
                            for (let index = 0; index < res.data.Msgs?.length; index++) {
                                const item = res.data.Msgs[index];
                                if (item.F == userInfo.Id && [0, 2, 3, 4, 5].indexOf(item.MT) !== -1) return // 过滤自己发的
                                realm.create(schemaName.GroupMsgLis, { ...item, G: element.G, _id: new Realm.BSON.UUID(), UserId: UserId }, true)
                            }
                        })
                    }
                }
            }
            catch (error) {
                console.log(error)
            }
            store.dispatch((dispatch) => {
                dispatch({ type: 'wallet/SetIsWallet', payload: true })
            })
        }

        SplashScreen.hide()

        store.dispatch((dispatch) => {
            dispatch({ type: 'app/setIsLoadingLoadFrom', payload: false })
        })

    }
    return {
        loadInitialData
    }
}


